package com.controller.vecc;

import com.alibaba.fastjson.JSONObject;
import com.common.anntation.Log;
import com.common.emums.BusinessType;
import com.common.python.ToolTest;
import com.common.utils.DateUtils;
import com.common.utils.EntityConversionUtil;
import com.common.utils.StringUtils;
import com.common.utils.UploadConfig;
import com.common.utils.nrmm.NrmmUtils;
import com.github.pagehelper.PageInfo;
import com.model.base.PageResult;
import com.model.base.Result;
import com.model.domain.system.GetSystemDeviceModelInfoDO;
import com.model.domain.user.GetUserInfoDO;
import com.model.domain.vecc.GetVeccDeviceModelAuthRecordInfoDO;
import com.model.domain.vecc.GetVeccRequestLogInfoDO;
import com.model.dto.common.AuthorizeFileDTO;
import com.model.dto.common.TboxFactoryLicenceImgDTO;
import com.model.dto.common.TerminalRecordAuthAddDTO;
import com.model.dto.vecc.deviceModelAuth.GetAuthRecordListDTO;
import com.model.dto.vecc.deviceModelAuth.GetDeviceModelAuthListDTO;
import com.model.dto.vecc.deviceModelAuth.SaveDeviceModelAuthInfoDTO;
import com.model.pojo.system.SystemDeviceModelInfo;
import com.model.pojo.user.UserInfo;
import com.model.pojo.vecc.VeccDeviceModelAuthRecordInfo;
import com.model.pojo.vecc.VeccRequestLogInfo;
import com.model.vo.common.VeccRequestVO;
import com.model.vo.common.VeccReturnVO;
import com.model.vo.vecc.deviceModelAuth.getAuthRecordList.GetAuthRecordListVO;
import com.model.vo.vecc.deviceModelAuth.getDeviceModelAuthList.GetDeviceModelAuthListVO;
import com.service.system.SystemDeviceModelInfoService;
import com.service.user.UserInfoService;
import com.service.vecc.VeccDeviceModelAuthRecordInfoService;
import com.service.vecc.VeccRequestLogInfoService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.Valid;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * TODO
 *
 * @Description
 * @Author tm
 * @Date 2024-02-21 12:58
 **/
@Api(tags = {"国四监控 - 终端型号授权管理"})
@Slf4j
@RestController
@RequestMapping("/v1/vecc/deviceModelAuth")
@RequiredArgsConstructor
public class VeccDeviceModelAuthController {
    private final VeccDeviceModelAuthRecordInfoService veccDeviceModelAuthRecordInfoService;
    private final UserInfoService userInfoService;
    private final SystemDeviceModelInfoService systemDeviceModelInfoService;
    private final VeccRequestLogInfoService veccRequestLogInfoService;
    @Log(title = "终端型号授权管理-获取授权列表", businessType = BusinessType.SELECT)
    @ApiOperation(value = "获取授权列表")
    @PostMapping("/getDeviceModelAuthList")
    public Result<PageResult<List<GetDeviceModelAuthListVO>>> getDeviceModelAuthList(@RequestBody @Valid GetDeviceModelAuthListDTO dto) {
        List<GetDeviceModelAuthListVO> voList = new ArrayList<>();
        GetVeccDeviceModelAuthRecordInfoDO getVeccDeviceModelAuthRecordInfoDO = EntityConversionUtil.copy(dto,GetVeccDeviceModelAuthRecordInfoDO.class);
        List<VeccDeviceModelAuthRecordInfo> recordList = veccDeviceModelAuthRecordInfoService.getPageList(getVeccDeviceModelAuthRecordInfoDO);
        if(recordList!=null && recordList.size()>0){
            List<Long> factoryUserIds = recordList.stream().map(VeccDeviceModelAuthRecordInfo::getFactoryUserId).collect(Collectors.toList());
            GetUserInfoDO getUserInfoDO = new GetUserInfoDO();
            getUserInfoDO.setIds(factoryUserIds);
            getUserInfoDO.setSortRow("id");
            Map<Long, UserInfo> userMap = userInfoService.getAllList(getUserInfoDO).stream().collect(Collectors.toMap(UserInfo::getId, Function.identity()));;
            List<Long> modelIds = recordList.stream().map(VeccDeviceModelAuthRecordInfo::getModelId).collect(Collectors.toList());
            GetSystemDeviceModelInfoDO getSystemDeviceModelInfoDO = new GetSystemDeviceModelInfoDO();
            getSystemDeviceModelInfoDO.setIdList(modelIds);
            getSystemDeviceModelInfoDO.setSortRow("id");
            Map<Long, SystemDeviceModelInfo> modelMap = systemDeviceModelInfoService.getAllList(getSystemDeviceModelInfoDO).stream().collect(Collectors.toMap(SystemDeviceModelInfo::getId,Function.identity()));
            recordList.forEach(item ->{
                GetDeviceModelAuthListVO vo = EntityConversionUtil.copy(item,GetDeviceModelAuthListVO.class);
                String factoryName = "";
                if(userMap.get(item.getFactoryUserId())!=null) factoryName = userMap.get(item.getFactoryUserId()).getName();
                vo.setFactoryName(factoryName);
                String deviceModel = "";
                if(modelMap.get(item.getModelId())!=null) deviceModel = modelMap.get(item.getModelId()).getName();
                vo.setDeviceModel(deviceModel);
                voList.add(vo);
            });
        }
        PageInfo<VeccDeviceModelAuthRecordInfo> pageInfo = new PageInfo<>(recordList);
        PageResult<List<GetDeviceModelAuthListVO>> build = PageResult.<List<GetDeviceModelAuthListVO>>builder().result(voList).pageInfo(pageInfo).build();
        return Result.suc(build);
    }

    @Log(title = "终端型号授权管理-保存终端型号授权信息", businessType = BusinessType.INSERT)
    @ApiOperation(value = "保存终端型号授权信息")
    @PostMapping("/saveDeviceModelAuthInfo")
    public Result<Objects> saveDeviceModelAuthInfo(@RequestBody @Valid SaveDeviceModelAuthInfoDTO dto) {
        int num = 0;
        long recordId = 0l;
        if(StringUtils.isBlank(dto.getFileUrl())){
            return Result.fail("9999","授权书不能为空");
        }
        if(dto.getModelId() == null || dto.getModelId() == 0){
            return Result.fail("9999","终端型号不为空");
        }
        SystemDeviceModelInfo deviceModelInfo = systemDeviceModelInfoService.getById(dto.getModelId());
        if(deviceModelInfo == null){
            return Result.fail("9999","终端型号不存在");
        }
        if(dto.getRecordId()!=null && dto.getRecordId()>0) {
            VeccDeviceModelAuthRecordInfo recordInfo = veccDeviceModelAuthRecordInfoService.getById(dto.getRecordId());
            if(recordInfo == null){
                return Result.fail("9999","记录不存在");
            }
            if(recordInfo.getStatus() == 2){
                return Result.fail("9999","已授权成功");
            }
            recordInfo.setFactoryUserId(dto.getFactoryUserId());
            recordInfo.setModelId(dto.getModelId());
            recordInfo.setFileUrl(dto.getFileUrl());
            if(dto.getType() == 1){//保存
                recordInfo.setStatus(0);
            }else if(dto.getType() == 2){//提交审核
                recordInfo.setStatus(1);
                recordInfo.setRequestId("");
            }
            num = veccDeviceModelAuthRecordInfoService.update(recordInfo);
            recordId = recordInfo.getRecordId();
        }else {
            VeccDeviceModelAuthRecordInfo recordInfo = new VeccDeviceModelAuthRecordInfo();
            recordInfo.setFactoryUserId(dto.getFactoryUserId());
            recordInfo.setModelId(dto.getModelId());
            recordInfo.setFileUrl(dto.getFileUrl());
            if(dto.getType() == 1){//保存
                recordInfo.setStatus(0);
            }else if(dto.getType() == 2){//提交审核
                recordInfo.setStatus(1);
                recordInfo.setRequestId("");
            }
            num = veccDeviceModelAuthRecordInfoService.save(recordInfo);
            recordId = recordInfo.getRecordId();
        }
        if(num > 0) {
            UserInfo userInfo = userInfoService.getById(dto.getFactoryUserId());
            if(dto.getType() == 2 && StringUtils.isNotBlank(userInfo.getForwardAccount()) && StringUtils.isNotBlank(userInfo.getForwardPwd())){//提交给环保部

                TerminalRecordAuthAddDTO terminalRecordAuthAddDTO = new TerminalRecordAuthAddDTO();
                terminalRecordAuthAddDTO.setTboxModel(deviceModelInfo.getName());
                terminalRecordAuthAddDTO.setOrganizationCode("91440101MA5ANH7Q4G");
                terminalRecordAuthAddDTO.setOrganizationName("广州市智慧农林科技有限公司");
                terminalRecordAuthAddDTO.setOrganizationExplain("智慧农林");
                terminalRecordAuthAddDTO.setContacts("陈宏伟");
                terminalRecordAuthAddDTO.setContactsTel("18027198185");

                TboxFactoryLicenceImgDTO tboxFactoryLicenceImgDTO = new TboxFactoryLicenceImgDTO();
                tboxFactoryLicenceImgDTO.setType("jpg");
                tboxFactoryLicenceImgDTO.setFileName(DateUtils.parseDateToStr(new Date(),DateUtils.DATE_TIME_FORMAT_YYYYMMDDHHMISSSSS));
                String value1 = ToolTest.imageBase64("/zhnl/ftp/upload/profile/other/zhihui.jpg");
                tboxFactoryLicenceImgDTO.setValue(value1);
                terminalRecordAuthAddDTO.setTboxFactoryLicenceImg(tboxFactoryLicenceImgDTO);

                AuthorizeFileDTO authorizeFileDTO = new AuthorizeFileDTO();
                authorizeFileDTO.setType("jpg");
                authorizeFileDTO.setFileName(DateUtils.parseDateToStr(new Date(),DateUtils.DATE_TIME_FORMAT_YYYYMMDDHHMISSSSS));
                int index = dto.getFileUrl().indexOf("profile");
                String filePath = UploadConfig.getFilePath()+dto.getFileUrl().substring(index+8,dto.getFileUrl().length());
                String value2 =ToolTest.imageBase64(filePath);
                authorizeFileDTO.setValue(value2);
                terminalRecordAuthAddDTO.setAuthorizeFile(authorizeFileDTO);

                String token = "";
                VeccReturnVO loginVo = NrmmUtils.recordLogin(userInfo.getForwardAccount(),userInfo.getForwardPwd());
                if(loginVo.getCode() == 200 &&StringUtils.isNotBlank(loginVo.getResultVO().getToken())){
                    token = loginVo.getResultVO().getToken();
                }
                VeccRequestLogInfo veccRequestLogInfo = new VeccRequestLogInfo();
                VeccRequestVO veccRequestVO = loginVo.getRequestVO();
                veccRequestLogInfo.setRecordId(recordId);
                veccRequestLogInfo.setRequestUrl(veccRequestVO.getRequestUrl());
                veccRequestLogInfo.setContent(veccRequestVO.getContent());
                veccRequestLogInfo.setResult(veccRequestVO.getResult());
                veccRequestLogInfo.setType(1);//登录
                veccRequestLogInfo.setStatus(1);
                veccRequestLogInfoService.save(veccRequestLogInfo);
                if(StringUtils.isNotBlank(token)) {
                    VeccReturnVO veccReturnVO = NrmmUtils.terminalRecordAuthAdd(terminalRecordAuthAddDTO, token);
                    VeccRequestLogInfo logInfo = new VeccRequestLogInfo();
                    logInfo.setRecordId(recordId);
                    logInfo.setRequestUrl(veccReturnVO.getRequestVO().getRequestUrl());
                    logInfo.setContent(veccReturnVO.getRequestVO().getContent());
                    logInfo.setResult(veccReturnVO.getRequestVO().getResult());
                    logInfo.setType(4);
                    boolean flag = false;
                    if(veccReturnVO.getCode() == 200 ){
                        if("该终端型号已授权".equals(veccReturnVO.getMessage())){
                            logInfo.setStatus(1);
                            logInfo.setRemark(veccReturnVO.getMessage());
                            logInfo.setAuditTime(new Date());
                            flag = true;
                        }else {
                            logInfo.setRequestId(veccReturnVO.getResultVO().getRequestID());
                            logInfo.setStatus(0);
                        }
                    }else{
                        flag = true;
                        logInfo.setStatus(2);
                        logInfo.setRemark(veccReturnVO.getMessage());
                        logInfo.setAuditTime(new Date());
                    }
                    veccRequestLogInfoService.save(logInfo);
                    if(flag){
                        VeccDeviceModelAuthRecordInfo recordInfo = veccDeviceModelAuthRecordInfoService.getById(recordId);
                        recordInfo.setStatus(logInfo.getStatus()+1);
                        recordInfo.setAuthTime(new Date());
                        veccDeviceModelAuthRecordInfoService.update(recordInfo);
                    }
                }
            }
            return Result.suc();
        }
        return Result.fail("9999","提交失败");
    }

    @Log(title = "终端型号授权管理-获取授权记录列表", businessType = BusinessType.SELECT)
    @ApiOperation(value = "获取授权记录列表")
    @PostMapping("/getAuthRecordList")
    public Result<PageResult<List<GetAuthRecordListVO>>> getAuthRecordList(@RequestBody @Valid GetAuthRecordListDTO dto) {
        List<GetAuthRecordListVO> voList = new ArrayList<>();
        GetVeccRequestLogInfoDO getVeccRequestLogInfoDO = new GetVeccRequestLogInfoDO();
        getVeccRequestLogInfoDO.setRecordId(dto.getRecordId());
        getVeccRequestLogInfoDO.setType(4);//终端授权备案
        getVeccRequestLogInfoDO.setSortRow("createdTime");
        List<VeccRequestLogInfo> logList = veccRequestLogInfoService.getAllList(getVeccRequestLogInfoDO);
        if(logList!=null && logList.size()>0){
            logList.forEach(item->{
                GetAuthRecordListVO vo = EntityConversionUtil.copy(item,GetAuthRecordListVO.class);
                vo.setSubmitTime(item.getCreatedTime());
                voList.add(vo);
            });
        }
        PageInfo<VeccRequestLogInfo> pageInfo = new PageInfo<>(logList);
        PageResult<List<GetAuthRecordListVO>> build = PageResult.<List<GetAuthRecordListVO>>builder().result(voList).pageInfo(pageInfo).build();
        return Result.suc(build);
    }
}
